package com.edeweiss.community.servlet;

import com.edeweiss.community.domain.*;
import com.edeweiss.community.services.AdminService;
import com.edeweiss.community.services.CommunityService;
import com.edeweiss.community.services.StudentService;
import com.edeweiss.community.services.servicesImp.AdminServiceImp;
import com.edeweiss.community.services.servicesImp.CommunityServiceImpl;
import com.edeweiss.community.services.servicesImp.StudentServiceImp;
import com.edeweiss.community.web.utils.UUIDUtils;
import com.mysql.cj.Session;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/StudentServlet")
public class StudentServlet extends BaseServlet {

    private StudentService studentService=new StudentServiceImp();
    private CommunityService communityService = new CommunityServiceImpl();
    private AdminService adminService = new AdminServiceImp();
    //注册
    public String regiStudent(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

        //检查验证码
        String yzm = request.getParameter("yzm");
        HttpSession session = request.getSession();
        String randomCode = (String) session.getAttribute("randomCode");
        session.removeAttribute("randomCode"); //保证验证码只能使用一次
        //比较
        if (yzm == null || !randomCode.equalsIgnoreCase(yzm)) {
            //提示信息
            request.setAttribute("error_msg","验证码错误！");
            //验证码错误
            return "reginForm.jsp";
        }

        String sno = request.getParameter("sno");
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        String sfaculty = request.getParameter("sfaculty");
        String telphone = request.getParameter("phonenumber");
        String gender = request.getParameter("gender");
        String sBirthday=request.getParameter("birthday");

        //创建学生实例
        Student student=new Student();
        student.setSid(UUIDUtils.getUUID());
        student.setSno(sno);
        student.setSusername(name);
        student.setSpassword(password);
        student.setSsex(gender);
        student.setSfaculty(Integer.parseInt(sfaculty));
        student.setStelphone(telphone);
        student.setBirthday(sBirthday);
        //注册
        int reginResult=studentService.ReginStudent(student);
        if(reginResult==1){
            //注册成功
            return "loginForm.jsp";
        }else{
            //注册失败
            request.setAttribute("msg","注册失败");
            return "ReginForm.jsp";
        }
    }

    //退出登陆
    public String exit(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect("index.jsp");
        return "/index.jsp";
    }

    //修改密码
    public String ChangePassword(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        //检查验证码
        String yzm = request.getParameter("yzm");
        HttpSession session = request.getSession();
        String randomCode = (String) session.getAttribute("randomCode");
        session.removeAttribute("randomCode");//保证验证码只能用一次

        if (yzm == null || !randomCode.equalsIgnoreCase(yzm)) {
            //提示信息
            request.setAttribute("msg", "验证码错误");
            return "loginForm.jsp";
        }

        String sno=request.getParameter("sno");
        String password=request.getParameter("newPassword");
        String oldPassword=request.getParameter("oldPassword");
        Student student=new Student();
        student.setSpassword(oldPassword);
        student.setSno(sno);
        int result=studentService.ChangePassword(student,password);
        //修改密码
        if(result==1){
            //修改成功
            response.sendRedirect("loginForm.jsp");
            return "";
        }else{
            //修改失败
            request.setAttribute("msg","修改失败");
            return "changePsword.jsp";
        }
    }

    //登陆
    public String login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

        //检查验证码
        String yzm = request.getParameter("yzm");
        HttpSession session = request.getSession();
        String randomCode = (String) session.getAttribute("randomCode");
        session.removeAttribute("randomCode");//保证验证码只能用一次

        if (yzm == null || !randomCode.equalsIgnoreCase(yzm)) {
            System.out.println("验证吧错误");
            //提示信息
            request.setAttribute("msg", "验证码错误");
            return "loginForm.jsp";
        }
        //获取登陆的权限
        String power = request.getParameter("power");
        //获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if("xs".equals(power)){
            //学生登陆
            Student stu=new Student();
            stu.setSno(username);
            stu.setSpassword(password);

            Student student=studentService.loginStudent(stu);
            if(student != null){
                request.getSession().setAttribute("student",student);
                response.sendRedirect("person/personInfo.jsp");
            }
            else{
                request.setAttribute("msg","用户名或密码错误！");
                return "loginForm.jsp";
            }
        }else if("sz".equals(power)){
            //社长登陆
            Student s = new Student();
            s.setSno(username);
            s.setSpassword(password);
            //调用service层进行登陆
            Responsibility rp = communityService.login(s);
            if(rp != null){
                //登陆成功
                request.getSession().setAttribute("sz",rp);
                response.sendRedirect("community/index.jsp");
            }else{
                request.setAttribute("msg","用户名或密码错误！");
                return "loginForm.jsp";
            }

        }else{
            Admin a = new Admin();
            a.setMid(username);
            a.setPassword(password);
            //管理员登陆
            Admin admin = adminService.login(a);
            if(admin == null){
                request.setAttribute("msg","用户名或密码错误！");
                return "loginForm.jsp";
            }else {
                request.getSession().setAttribute("admin",admin);
                response.sendRedirect("pages/index.jsp");
            }
        }
        return "";
    }

    //查询学院
    public String findFactoryId(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        List<Faulty> faulties = studentService.findFaultyId();
        request.getSession().setAttribute("faulties",faulties);
        return "ReginForm.jsp";
    }

    //查询我加入的社团
    public String findJoinCommunity(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        //获取学生的id
        String sid = request.getParameter("sid");
        List<Community> communities = studentService.findJoinCommunity(sid);
        if(communities != null && communities.size()>0){
            request.getSession().setAttribute("join",communities);
            response.sendRedirect("person/personInfo.jsp");
        }else {
            request.getSession().setAttribute("msg","你还未加入任何社团");
            response.sendRedirect("person/index.jsp");
        }
        return "";
    }

    //查询所有的社团
    public String findAllCommunity(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        List<Community> communities = communityService.findAll();
        request.getSession().setAttribute("all",communities);
        response.sendRedirect("person/joinCommunityApprove.jsp");
        return "";
    }

    //学生申请加入社团
    public String applyJoinCommunity(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        CommunityApply apply = new CommunityApply();
        //学生的id
        String sid = request.getParameter("sid");
        //简历
        String resume = request.getParameter("resume");
        //加入社团的id
        String cid = request.getParameter("cid");
        apply.setResume(resume);
        apply.setSid(sid);
        apply.setTime(new Date());
        apply.setStatus(0);
        apply.setName(Integer.parseInt(cid));

        int flag = studentService.applyJoinCommunity(apply);
        if(flag == 1){
            //申请成功，等待处理
            request.getSession().setAttribute("msg","申请成功，请等待社长处理！");
        }else {
            request.getSession().setAttribute("msg","申请失败，请重新尝试！");
        }
        response.sendRedirect("person/index.jsp");
        return "";
    }

    //申请加入名人堂
    public String applyHof(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取文件上传组件
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fileItemFactory);

        //创建名人堂对象
        Hof hof = new Hof();
        hof.setDate(new Date());
        hof.setStatus(0);
        String sid = request.getParameter("sid");
        hof.setSid(sid);

        String uploadPath = null;
        try{
            //获取上传文件的项目
            List<FileItem> items = upload.parseRequest(request);
            for(FileItem item:items){
                //上传的是普通文件
                if(item.isFormField()){
                    //获取申请学生的id
                   if("material".equals(item.getFieldName())){
                        String material = new String(item.get(),"utf-8");
                        hof.setExperience(material);
                    }
                }else{
                    String filName=item.getName();
                    String prefix = UUIDUtils.getUUID();
                    String subfix = filName.substring(filName.lastIndexOf("."));
                    //获取文件上传目录路径，在项目部署路径下的upload目录里。若想让浏览器不能直接访问到图片，可以放在WEB-INF下
                    uploadPath=this.getServletContext().getRealPath("/uploadImg");
                    //写入文件到磁盘，该行执行完毕后，若有该临时文件，将会自动删除
                    item.write(new File(uploadPath,prefix+subfix));
                    hof.setImg(prefix+subfix);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //调用service层进行提交
        int flag = studentService.applyHof(hof);
        if(flag == 1){
            request.getSession().setAttribute("msg","申请成功，等待管理员审核！");
        }else{
            request.getSession().setAttribute("msg","申请失败，请再次尝试！");
        }
        //请求重定向
        response.sendRedirect("person/index.jsp");
        /*String sid = request.getParameter("sid");
        String material = request.getParameter("material");

        Hof hof = new Hof();
        hof.setDate(new Date());
        hof.setStatus(0);

        hof.setExperience(material);
        hof.setSid(sid);

        //调用service层进行提交
        int flag = studentService.applyHof(hof);
        if(flag == 1){
            request.getSession().setAttribute("msg","申请成功，等待管理员审核！");
        }else{
            request.getSession().setAttribute("msg","申请失败，请再次尝试！");
        }
        //请求重定向
        response.sendRedirect("person/index.jsp");*/
        return "";
    }

    //查询回复的消息
    public String findMessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sid = request.getParameter("sid");

        //调用service层进行提交
        List<Message> messages= studentService.findMessage(sid);

        if(messages != null && messages.size()>0){
            request.getSession().setAttribute("messages",messages);
            response.sendRedirect("person/letter.jsp");
        }else {
            request.getSession().setAttribute("msg","你还没有任何消息");
            //请求重定向
            response.sendRedirect("person/index.jsp");
        }

        return "";
    }
}
